<template>
    <div id="peszs">
        <n-spin :show="loadstatus">
            <div class="content" v-if="serverArr.length > 0">

                <card-server v-for="(item, index) in serverArr" :key="index" :item="item" @click="uigo(item.uuid)"
                    @delResult="delResult"></card-server>

            </div>
            <template v-else>
                <n-empty description="您还没有服务器">
                    <template #extra>
                        <n-button @click="active = true" size="small" strong secondary type="primary">
                            创建一个
                        </n-button>
                    </template>
                </n-empty>
            </template>
        </n-spin>
    </div>
    <!-- 悬浮按钮 -->
    <div class="suspend" v-if="serverArr.length > 0">
        <n-button strong circle type="success" size="large" @click="active = true">
            <template #icon>
                <i class="iconfont icon-chuangjian"></i>
            </template>
        </n-button>
    </div>


    <n-drawer v-model:show="active" placement="top" to="#peszs" default-height="75%">
        <n-drawer-content>
            <template #header>
                新建服务器
            </template>

            <n-form ref="formRef" :model="dynamicForm">
                <n-form-item label="服务器名称" path="serverName" :rule="{
                    required: true,
                    message: '请输入正确的服务器名称',
                    trigger: ['input', 'blur']
                }">
                    <n-input-group>
                        <n-input v-model:value="dynamicForm.serverName" placeholder="请输入服务器名称" clearable>
                            <template #prefix>
                                <i class="iconfont icon-bianji0"></i>
                            </template>
                        </n-input>
                    </n-input-group>
                </n-form-item>

                <!-- 只有新增的时候才会用 服务器类型-->

                <n-form-item path="serverType" label="服务器类型" :rule="{
                    required: true,
                    message: '请选择服务器类型',
                    trigger: ['change']
                }">
                    <template #label>
                        <i class="iconfont icon-fuwuleixing"></i>
                        服务器类型
                    </template>
                    <n-select v-model:value="dynamicForm.serverType" :options="toolStore.serverTypeOptions"
                        placeholder="请选择服务器类型" @update:value="serverTypeupdate" />

                </n-form-item>

                <!-- 不是通用控制台 -->
                <div
                    v-if="dynamicForm.serverType != 'console' && dynamicForm.serverType != 'sharePack' && dynamicForm.serverType">
                    <n-form-item path="serverPackagev" label="版本包" :rule="{
                        required: true,
                        validator: resPackValidator,
                        message: '请选择版本包',
                        trigger: ['change']
                    }">
                        <template #label>
                            <i class="iconfont icon-bushubanben"></i>
                            版本包
                            <!-- <n-button size="tiny" strong type="warning" round>
                                我要投递
                            </n-button> -->
                        </template>
                        <n-select v-model:value="dynamicForm.serverPackagev" :options="packagevs" placeholder="请选择版本包"
                            @update:value="typeResUpdate" />
                    </n-form-item>


                    <div v-if="dynamicForm.serverPackagev">
                        <!-- 提示下载 -->
                        <n-form-item path="resPackpercentage" label="包下载状态" :rule="{
                            required: true,
                            validator: downloadStatus, trigger: ['change']
                        }">
                            <template #label>
                                <i class="iconfont icon-wenjian-yasuobao"></i>
                                下载状态（{{ dynamicForm.percentage ?? 0 }}%）
                            </template>
                            <n-progress type="line" status="success" :percentage="dynamicForm.percentage ?? 0" :height="15"
                                :indicator-placement="!dynamicForm.percentage ? 'outside' : 'inside'">
                                <n-button size="tiny" type="success" round @click="downloadNow" :loading="downloadloading">
                                    下载 </n-button>
                            </n-progress>
                        </n-form-item>
                    </div>


                </div>

                <!-- 选择分享包 -->
                <div v-if="dynamicForm.serverType == 'sharePack'">
                    <n-form-item label="选择资源包" path="serverPack" :rule="{
                        required: true,
                        validator: packagevalidator,
                        trigger: ['input', 'blur']
                    }">
                        <n-input-group>
                            <n-input :disabled="false" v-model:value="dynamicForm.serverPack" placeholder="请输入资源包"
                                clearable>
                                <template #prefix>
                                    <i class="iconfont icon-wenjian-yasuobao"></i>
                                </template>
                            </n-input>
                            <n-button type="primary" @click="checkmark">
                                选择资源包
                            </n-button>
                        </n-input-group>
                    </n-form-item>
                </div>


            </n-form>
            <n-button type="primary" size="small" @click="handleValidateButtonClick" :loading="submitloading">
                <template #icon>
                    <i class="iconfont icon-zhengque"></i>
                </template>
                新建
            </n-button>

        </n-drawer-content>
    </n-drawer>
</template>
  
  
<script setup>
import { ref, reactive, onActivated, onDeactivated, computed, toRaw } from "vue";
import { useToolStore, useMainStore } from "@renderer/store/index";
import { useRouter } from 'vue-router';
import { useMessage, useDialog } from 'naive-ui';
import { getResPackages } from '@renderer/assets/common/api';

const dialog = useDialog();
const router = useRouter();
const toolStore = useToolStore();
const mainStore = useMainStore();
// 组件
import cardServer from "@renderer/components/card-server.vue";

let { ipcRenderer } = window.electron;

const message = useMessage();

const loadstatus = ref(true);//加载状态
const downloadloading = ref(false);//下载按钮是否加载中
const submitloading = ref(false);//确定保存的加载状态

const formRef = ref(null);
let dynamicForm = reactive({});//新建菜单的数据
const packagevs = computed(() => {
    return mainStore.resPackages[dynamicForm.serverType] ?? [];//返回指定类型包的列表
});//资源包选择列表
const active = ref(false);

let serverArr = ref([]);

//监听下载进度
ipcRenderer.on('download_file_progress', (e, progress) => {
    dynamicForm.percentage = progress;//更新进度
});

function downloadStatus(rule, value) {
    value = dynamicForm.percentage;
    return (value == undefined || value < 100) ? new Error(" 请先下载资源包") : true;
}

function resPackValidator(rule, value) {
    if (!value) {
        return new Error(" 请选择版本包");
    }
    return true;
}


onActivated(async () => {
    // message.error('发生错误了，嘻嘻假的！');

    let serList = await window.api.getItemList();//获取项目列表
    if(serList==null){
        message.error('获取项目列表失败，请重试（极大可能是没有权限，请用管理员运行）！');
        return;
    }
    serverArr.value = serList;//刷新列表
    loadstatus.value = false;//隐藏加载


});


onDeactivated(() => {
    loadstatus.value = true;//显示加载
});

/**
 * 点击确定
 */
function handleValidateButtonClick() {
    formRef.value?.validate((errors) => {
        if (!errors) {
            if (submitloading.value) return;//防止重复点击
            submitloading.value = true;//设置按钮加载中
            let resPackPath = '';//资源包地址
            if (dynamicForm.serverType != 'console' && dynamicForm.serverType != 'sharePack') {
                // 官方资源包才有uuid
                resPackPath = window.api.getAssignResPath(dynamicForm.serverPackagev.uuid);//获取资源包路径
            }
            if (dynamicForm.serverType == 'sharePack') {
                // 分享包
                resPackPath = dynamicForm.serverPack;
            }
            let contentS = `正在创建 [ ${dynamicForm.serverName} ] 请等待！`;
            const del = dialog.warning({
                title: "温馨提示",
                content: contentS,
                closable: false,
                closeOnEsc: false,
                maskClosable: false,
                loading: true
            });
            let hintDs = null;
            if (dynamicForm.serverType != 'console') {
                let hintArr = ['...创建配置文件！', '...创建项目目录！', '...解压资源包！'];
                let count = 0;
                hintDs = setInterval(() => {
                    if (count > (hintArr.length - 1)) {
                        del.content = contentS + hintArr[(hintArr.length - 1)] + (count % 2 ? '~~' : '~');
                    } else {
                        del.content = contentS + hintArr[count];
                    }
                    count++;
                }, 1000);
            }
            window.api.createItem(dynamicForm.serverName, dynamicForm.serverType, resPackPath).then(result => {
                if (hintDs) clearInterval(hintDs);
                submitloading.value = false;//设置按钮不加载中
                if (!result.status) {
                    del.destroy();//关闭弹窗
                    message.error(result.msg);
                    return;
                }
                active.value = false;//隐藏抽屉
                del.destroy();//关闭弹窗
                dynamicForm = reactive({});//清空信息
                message.success('创建成功！');
                window.api.getItemList().then(res => {
                    serverArr.value = res;//刷新列表
                });//获取项目列表
            }).catch(err => {
                if (hintDs) clearInterval(hintDs);
                submitloading.value = false;//设置按钮不加载中
                del.destroy();//关闭弹窗
                message.error(`资源包解压失败：${err.message}`);
            });//创建服务器
        } else {
            submitloading.value = false;//设置按钮不加载中
            message.error(errors[0][0].message);
        }
    });
}

/**
 * 删除结果
 * @param {boolean} status 
 */
function delResult(status) {
    if (!status) {
        message.error("删除失败了！");
        return;
    }
    message.success('删除成功！');
    window.api.getItemList().then(res => {
        serverArr.value = res;//刷新列表
    });//获取项目列表
}

function uigo(uuid) {
    router.push({ path: '/server/console', query: { uuid } });
}
/**
 * 下载资源包
 */
async function downloadNow() {
    downloadloading.value = true;//设置按钮加载中
    let dinfo = dynamicForm.serverPackagev;
    let pResult = { data: dinfo.url };
    if (dinfo.urlType == 123) {
        pResult = await window.api.d123panparse(dinfo.url);
        if (!pResult.status) {
            // 解析失败
            message.error('泰库拉，数据包解析错误！请通知作者更新软件！（为啥要用解析，因为作者没有服务器！没地方存放！）');
            return;
        }
    }


    await ipcRenderer.invoke('download_file', pResult.data, dinfo.uuid);
}
/**
 * 服务器类型选择器更新事件
 * @param {string} value 
 */
function serverTypeupdate(value) {
    dynamicForm.serverPackagev = null;
    /**
     * 获取最新的 资源包列表
     */
    getResPackages().then(res => {
        mainStore.resPackages = res;
    });

}

/**
 * 类型包选择器更新事件
 * @param {string} value 
 */
function typeResUpdate(value) {
    downloadloading.value = false;//设置按钮没有加载
    if (!value.uuid) {
        dynamicForm.percentage = 0;
        return;
    }
    let result = window.api.isAssignRes(value.uuid);
    if (result) {
        dynamicForm.percentage = 100;
        return;
    }
    dynamicForm.percentage = 0;
}

/**
 * 选择资源包
 */
function checkmark() {
    window.api.showOpenDialog(false, [
        { name: '压缩资源包', extensions: ['zip', 'rar', 'gz'] }
    ]).then(result => {
        if (result.canceled) {
            // 是否已经取消选择
            return;
        }
        dynamicForm.serverPack = result.filePaths[0];//设置选择的目录
        formRef.value?.validate((errors) => {
            if (errors) {
                message.error(errors[0][0].message);
            }
        });
    });

}

/**
 * 分享码验证的
 * @param {*} rule 
 * @param {*} value 
 */
function packagevalidator(rule, value) {
    if (!value) {
        return new Error("请输入资源包路径");
    }
    return true;
}

</script>
  
  
<style lang="scss" scoped>
.content {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 10px;
}

.n-empty {
    margin-top: 30vh;
}

.suspend {
    position: absolute;
    bottom: 10vh;
    right: 5vw;
    z-index: 99;

    .n-button {
        box-shadow: 5px 5px 12px rgba(24, 160, 88, 0.6);
    }
}
</style>